/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useState, lazy } from "react";
import lazyLoad from "../hooks/lazyLoad";

export const context = createContext({});

/**
 * 路由扁平化处理
 * @param {*} menus
 * @returns
 */
function flatRoutes(menus) {
  const arr = [];
  function findInfo(data) {
    data.forEach((item) => {
      const { children, ...info } = item;
      arr.push(info);
      if (children) {
        findInfo(children);
      }
    });
  }
  findInfo(menus);
  return arr;
}
/**
 * role过滤权限
 * @param {*} role
 * @returns
 */
function findRoles(menus, role) {
  const arr = [];

  function findInfo(data, parent) {
    data.forEach((item) => {
      const { children, ...info } = item;
      //   children存在查找子集
      if (children) {
        info.children = [];
        findInfo(children, info.children);
        // 没有子节点就删除子节点
        // eslint-disable-next-line no-unused-expressions
        info.children.length === "0" ? delete info.children : null;
      }
      //children不存在就判断有没有权限
      if (info.roles) {
        // 有权限的情况下就判断有没有父节点，有父节点就是有二级路由，没有父节点就是一级路由，没有嵌套
        if (info.roles?.includes(role)) {
          parent ? parent.push(info) : arr.push(info);
        }
      } else {
        parent ? parent.push(info) : arr.push(info);
      }
    });
  }

  findInfo(menus);
  return arr;
}

// 实现动态路由的hooks必须
export default function AppProvider({ children }) {
  // 本地menu菜单roles: ["role"],//存在就展示，不存在就会过滤权限，在数组中就代表有权限
  let menusList = [
    {
      key: "/layouts/home",
      element: lazyLoad(lazy(() => import("@/view/home/Home.jsx"))),
      label: "首页",
    },
    {
      key: "/layouts/user",
      label: "用户管理",
      roles: ["admin", "role", "superAdmin"], //不存在就展示，存在就会过滤权限
      children: [
        {
          key: "/layouts/user/list",
          element: lazyLoad(lazy(() => import("@/view/user/UserList.jsx"))),
          roles: ["admin", "role", "superAdmin"],
          label: "用户列表",
        },
      ],
    },
  ];
  let defaultMenus = [];
  let defaultRoutes = [];
  let roles = sessionStorage.getItem("role");
  if (roles) {
    defaultMenus = findRoles(menusList, roles);
    if (defaultMenus && defaultMenus.length > 0) {
      defaultRoutes = flatRoutes(defaultMenus);
    }
  }
  // 侧边栏
  const [menus, setMenus] = useState(defaultMenus);
  // 路由
  const [routes, setRoutes] = useState(defaultRoutes);

  //根据当前角色生成路由信息和侧边栏信息
  const resetMenus = (role) => {
    // 此处重置菜单数据和路由数据
    const temMenu = findRoles(menusList, role);
    setMenus(temMenu);
    setRoutes(flatRoutes(temMenu));
  };

  return (
    <context.Provider value={{ menus, routes, resetMenus }}>
      {children}
    </context.Provider>
  );
}
